// @flow
import React, { Component } from 'react'
import styles from './Problem.css'
import { Button, Form, Modal, Select, Row, Col } from 'antd'
import ProblemGrid from './ProblemGrid'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { connect } from 'react-redux'
const Option = Select.Option
type Props = {
  userId: string,
  history: Object,
  form: Object
}
type States = {
  problemData: Array<Object>,
  total: number,
  current: number,
  pageSize: number,
  conditionVisible: boolean,
  conditionData: Object,
  selectVal: Object
}
class Problem extends Component {
  props: Props
  state: States
  queryUrl: String
  getPropblems: Function
  getCondition: Function
  openCondition: Function
  closeCondition: Function
  handleSearch: Function
  selectVal: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      problemData: [],
      total: 0,
      current: 1,
      pageSize: 20,
      conditionVisible: true,
      conditionData: {},
      selectVal: {}
    }
    this.getPropblems = this.getPropblems.bind(this)
    this.getCondition = this.getCondition.bind(this)
    this.openCondition = this.openCondition.bind(this)
    this.closeCondition = this.closeCondition.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.selectVal = this.selectVal.bind(this)
  }
  componentWillMount () {
    this.getPropblems(this.state.current, this.state.pageSize) // 列表信息
    this.getCondition() // 搜索条件
  }

  getPropblems (page: number, pageSize: number) {
    const { selectVal } = this.state
    let d
    let selectArr = []
    for (d in selectVal) {
      if (selectVal[d] !== '') {
        selectArr.push(d + '=' + selectVal[d])
      }
    }
    let condit = ''
    if (selectArr.length > 0) {
      condit = '&'
      condit += selectArr.join('&')
    }

    universalFetch(`${__SERVICE_API__}device/problem/problems?pageNum=${page}&pageSize=${pageSize}${condit}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          current: page,
          total: json.pageInfo.total,
          problemData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getCondition () {
    universalFetch(`${__SERVICE_API__}device/problem/list`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          conditionData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  handleSearch () {
    this.setState({
      conditionVisible: false,
      current: 1
    }, () => {
      this.getPropblems(this.state.current, this.state.pageSize)
    })
  }
  openCondition () {
    this.setState({
      conditionVisible: true
    })
  }
  closeCondition () {
    this.setState({
      conditionVisible: false
    })
  }
  selectVal (key: string, value: string) {
    this.setState({
      selectVal: Object.assign({}, this.state.selectVal, {
        [key]: value
      })
    })
  }
  render () {
    const component = this
    const { problemData, current, pageSize, total, conditionData } = this.state
    const selects = [
      ['vibrationDominantFrequency', '振动主导频率'],
      ['vibrationLoadChange', '振动随负荷变化'],
      ['vibrationDirection', '振动方向'],
      ['vibrationSpeedChange', '振动随转速变化'],
      ['withFrequency', '常伴频率'],
      ['vibrationOilChange', '振动随油温变化'],
      ['vibrationStability', '振动稳定性'],
      ['vibrationPressureChange', '振动随出口压力变化'],
      ['phaseCharacteristics', '相位特征'],
      ['rotorTrajectory', '转子轨迹']
    ]
    return (
      <div className={styles['main']}>
        <div className={styles['action']}>
          <Button type='primary' onClick={this.openCondition}>个例诊断</Button>
        </div>
        <ProblemGrid {...{
          current,
          pageSize,
          total,
          refreshCustomers: this.getPropblems,
          rowData: problemData,
          history: this.props.history
        }} />
        <Modal
          title='个例诊断'
          width={800}
          visible={this.state.conditionVisible}
          onCancel={this.closeCondition}
          onOk={this.handleSearch}
          >
          <div className={styles['conditionMain']}>
            {
              selects.map((data, index) => {
                const key = data[0]
                return <Row key={index} style={{ width: '50%', float: 'left' }}>
                  <Col span={10} style={{ textAlign: 'right', paddingRight: 10 }}>{data[1]}</Col>
                  <Col span={12}>
                    {
                      (<Select
                        key={index}
                        size='small'
                        style={{ width:'100%', color:'#999' }}
                        placeholder={data[1]}
                        showSearch
                        filterOption={(input, option, e) => {
                          return option.props.children.indexOf(input) >= 0
                        }}
                        // defaultValue=''
                        // value={selectVal[key]}
                        onChange={function (value) { component.selectVal(key, value) }}
                        >
                        <Option key='0' value=''>全部</Option>
                        {
                        conditionData[key] ? conditionData[key].map((d, i) => {
                          return <Option key={i + 1} value={d}>{d}</Option>
                        }) : ''
                        }
                      </Select>)
                    }
                  </Col>
                </Row>
              })
            }
          </div>
        </Modal>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(Problem))
